﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://wpfimageviewer.codeplex.com
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
#if COUNT_DRAW_OPERATIONS
using BrainTechLLC;
using BrainTechLLC.ThreadSafeObjects;
#endif
using System.Windows.Media.Imaging;

namespace BrainTechLLC.ImageOperatorsNonAForgeDependent
{
    public static class FileImageRotation
    {
        public static RotateFlipType GetRotateFlipType(this Rotation rotation, bool clockwise)
        {
            RotateFlipType rotationType = RotateFlipType.RotateNoneFlipNone;

            switch (rotation)
            {
                case Rotation.Rotate90:
                    rotationType = (clockwise) ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
                    break;

                case Rotation.Rotate270:
                    rotationType = (clockwise) ? RotateFlipType.Rotate270FlipNone : RotateFlipType.Rotate90FlipNone;
                    break;

                case Rotation.Rotate180:
                    rotationType = RotateFlipType.Rotate180FlipNone;
                    break;
            }

            return rotationType;
        }

        public static Bitmap Rotate(this Bitmap bm1, Rotation rotation, string outFile, bool clockwise, int resizeJpegQuality)
        {
            RotateFlipType rotationType = GetRotateFlipType(rotation, clockwise);

            if (rotationType != RotateFlipType.RotateNoneFlipNone)
            {
                JpegEncoding.SetJPEGConversionQuality(resizeJpegQuality);
                
                try
                {
                    bm1.RotateFlip(rotationType);
                    bm1.Save(outFile, JpegEncoding._jpegCodec, JpegEncoding._jpegParams);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return bm1;
                }
            }

            return bm1;
        }
    }
}
